<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\controller\Index;
use app\common\controller\Backend;
use think\Db;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdrawals extends Backend
{

    /**
     * Withdrawals模型对象
     * @var \app\admin\model\Withdrawals
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Withdrawals;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("withdrawalMethodList", $this->model->getWithdrawalMethodList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['id','nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    //提现审批
    public function audit()
    {
        $data = input(); // 获取所有 P
        // 获取请求的参数
        $ids = $data['ids']; // 获取所有 ID
        $status = $data['status']; // 获取审核状态
        $reason = $data['reason']; // 获取拒绝理由

        // 如果是单个数字，将其转成数组
        if (!is_array($ids)) {
            $ids = [(int)$ids]; // 将单个ID放入数组中
        } else {
            $ids = array_map('intval', $ids); // 确保数组中的每个值都是整数
        }

        // 验证输入
        if (empty($ids) || !is_array($ids)) {
            $this->error('无效的请求，必须提供一个有效的ID列表！');
        }
        Db::startTrans();
        // 执行状态更改及余额处理
        foreach ($ids as $id) {
            // 根据 ID 查询记录
            $withdrawRecord = $this->model->get($id);

            if($withdrawRecord->status!=0){
                continue;
            }
            if (!$withdrawRecord) {
                $this->error("ID {$id} 不存在");
            }
            $withdrawRecord->audit_time=time();
            $withdrawRecord->audit_admin_id=$this->auth->id;
            try {
                if ($status === 'approve') {
                    // 同意审核 - 修改状态为成功
                    $withdrawRecord->status = 'completed';

                    $userinfo=User::where('id','=',$withdrawRecord['user_id'])->find();
                    $info = [
                        'orderno' => $withdrawRecord->order_no,
                        'openid' => $userinfo['openid'],
                        'amount' => $withdrawRecord->amount,
                        'desc'   => '提现',
                    ];
                    $package_info = $this->tixian($info);
                    $withdrawRecord->package = $package_info;
                    $withdrawRecord->save(); // 保存更改
                } elseif ($status === 'reject') {
                    // 拒绝审核 - 修改状态为拒绝
                    $withdrawRecord->status = 'failed';
                    $withdrawRecord->audit_remark = $reason;
                    $withdrawRecord->save(); // 保存更改
                    // 退回骑手余额
                    Index::op_money($withdrawRecord['user_id'], $withdrawRecord['amount'], 'inc', '提现', '提现驳回', '提现驳回',$id);
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        Db::commit();
        $this->success("审核处理成功！");
    }


    //提现
    public function tixian($info = [])
    {
        if (empty($info)){
            return false;
        }
        $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
        $batch_name = '用户提现';
        $pars = [];
        $pars['appid'] = 'wx3fe363bbd726a5cc';//直连商户的appid
        $pars['out_bill_no'] =  $info['orderno'];//'sjzz'.date('Ymd').mt_rand(1000, 9999);//商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
        $pars['transfer_scene_id'] = '1005';
        $pars['openid']=$info['openid'];
        $pars['transfer_amount']=intval(strval($info['amount'] * 100));
        $pars['transfer_remark']=$batch_name;
        $pars['user_recv_perception']='劳务报酬';
        $pars['transfer_scene_report_infos'] = [
            [
                "info_type" => "岗位类型",
                "info_content" => "用户"
            ],
            [
                "info_type" => "报酬说明",
                "info_content" => "佣金"
            ],
        ];

//        $pars['batch_name']   = $batch_name;//该笔批量转账的名称
//        $pars['batch_remark'] = $batch_name;//转账说明，UTF8编码，最多允许32个字符
//        $pars['transfer_amount'] = intval(strval($info['amount'] * 100));//转账总金额 单位为“分”
//        $pars['total_num']    = 1;//转账总笔数
//        $pars['transfer_detail_list'][0]  = [
//            'out_detail_no'=> $info['orderno'],
//            'transfer_amount'=>intval(strval($info['amount'] * 100)),
//            'transfer_remark'=>$batch_name,
//            'openid'=>$info['openid'],
//        ];//转账明细列表
        $token  = $this->getToken($pars);//获取token
        $res    = $this->https_request($url,json_encode($pars),$token);//发送请求
        $resArr = json_decode($res,true);
        return $resArr['package_info'];
        //dump($resArr);die();
    }

    public function getToken($pars)
    {
        $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
        $http_method = 'POST';//请求方法（GET,POST,PUT）
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = json_encode((object)$pars);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        //证书
        $apiclient_cert_path =  ADDON_PATH . 'epay' . DS . 'certs' . DS . 'apiclient_cert.pem';
        $apiclient_key_path  = ADDON_PATH . 'epay' . DS . 'certs' . DS . 'apiclient_key.pem';

        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥

        $merchant_id = '1702146346';//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));

        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $token;
    }


    function https_request($url,$data = null,$token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        print_r($output);
        curl_close($curl);
        return $output;
    }

}
